<template>
    <div style="margin: 4px 4px 0px;">
      <div class="ant-row" style="margin-left: -12px; margin-right: -12px;">
        <div class="ant-col ant-col-md-24" style="padding-left: 12px; padding-right: 12px;">
          <div class="ant-card">
            <div class="ant-card-body">
              <div class="table-page-search-wrapper" style="margin-left: 20px;">
                <el-form :inline="true" :model="formInline" class="demo-form-inline">
                  <el-form-item label="单据编号：">
                    <el-input v-model="menu.billNo" placeholder="请输入单据编号" clearable class="input"
                      style="width: 280px; margin-left: 10px;" />
                  </el-form-item>
                  <el-form-item label="单据日期：">
                    <el-date-picker type="datetimerange" start-placeholder="开始时间" end-placeholder="结束时间"
                      format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd" time-format="A hh:mm:ss"
                      style="width: 280px; margin-left: 10px;" v-model="menu.billTime" />
                  </el-form-item>
                  <el-form-item label="客户：">
                    <el-select v-model="menu.supName" clearable style="width: 310px; margin-left: 10px;"
                      placeholder="请选择客户">
                      <el-option v-for="customer in show" :key="customer.id" :label="customer.supName"
                        :value="customer.supName" />
                    </el-select>


                  </el-form-item>
  
                  <el-form-item label="往来单位：">
                    <el-select v-model="menu.organId" clearable style="width: 280px; margin-left: 10px;"
                      placeholder="请选择往来单位">
                      <el-option v-for="customer in customers" :key="customer.id"
                        :label="`${customer.supName} ${customer.supType === '0' ? '[供应商]' : '[客户]'}`"
                        :value="customer.supId" />
                    </el-select>
                  </el-form-item>
  
                  <el-form-item>
                    <el-button type="primary" @click="loadMenus">查询</el-button>
                    <el-button @click="onReset">重置</el-button>
                    <a style="margin-left: 8px; color: #1890ff;" @click="toggle">
                      {{ expanded ? '收起' : '展开' }}
                      <i class="anticon anticon-down" :class="{ 'rotated': expanded }">
                        <svg viewBox="64 64 896 896" data-icon="down" width="1em" height="1em" fill="currentColor"
                          aria-hidden="true" focusable="false"
                          :style="{ transform: expanded ? 'rotate(180deg)' : 'rotate(0deg)' }">
                          <path
                            d="M884 256h-75c-5.1 0-9.9 2.5-12.9 6.6L512 654.2 227.9 262.6c-3-4.1-7.8-6.6-12.9-6.6h-75c-6.5 0-10.3 7.4-6.5 12.7l352.6 486.1c12.8 17.6 39 17.6 51.7 0l352.6-486.1c3.9-5.3.1-12.7-6.4-12.7z">
                          </path>
                        </svg>
                      </i>
                    </a>
                  </el-form-item>
  
                  <div v-if="expanded" class="additional-content">
                    <el-form-item label="操作员：">
                      <el-select v-model="menu.username" clearable style="width: 293px; margin-left: 10px;"
                        placeholder="请选择操作员">
                        <el-option v-for="user in users" :key="user.id" :label="user.username" :value="user.username" />
  
                      </el-select>
                    </el-form-item>
                    <el-form-item label="财务人员：">
                      <el-select v-model="menu.handsPersonId" clearable style="width: 300px; margin-left: 10px;"
                        placeholder="请选择财务人员">
                        <el-option v-for="persons in person" :key="persons.perId" :label="persons.perName"
                          :value="persons.perId" />
                      </el-select>
  
  
                    </el-form-item>
                    <el-form-item label="收入账户：">
                      <el-select v-model="menu.accountId" clearable style="width: 280px; margin-left: 10px;"
                        placeholder="请选择收入账户">
                        <el-option v-for="account in accounts" :key="account.id" :label="account.name"
                          :value="account.accId" />
                      </el-select>
  
  
                    </el-form-item>
                    <el-form-item label="单据状态：">
                      <el-select v-model="menu.status" clearable style="width: 240px; margin-left: 10px;"
                        placeholder="请选择单据状态">
                        <el-option v-for="status in stausData" :key="status.status" :label="status.stname"
                          :value="status.status" />
                      </el-select>
                    </el-form-item>
  
  
                    <el-form-item label="单据备注：">
                      <el-input v-model="menu.remark" placeholder="请输入单据备注" clearable style="width: 260px;" />
                    </el-form-item>
                  </div>
  
                </el-form>
              </div>
  
              <div class="table-wapper-box" style="margin-left: 20px;">
                <div class="table-operator" style="margin-top: 5px;">
                  <el-button type="primary" class="ant-btn ant-btn-primary" style="margin-right: 10px;" plain
                    v-perm:finance:receivables:collectioninsert="insert">
                    <el-icon class="el-icon-left">
                      <Plus />
                    </el-icon>
                    <span>新增</span>
                  </el-button>
                  <el-dropdown>
                    <el-button class="ant-btn ant-dropdown-trigger">
                      批量操作<el-icon class="el-icon--right">
                        <ArrowDown />
                      </el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item @click="deleteSelected">
                          <el-icon>
                            <Delete />
                          </el-icon>
                          <span>删除</span>
                        </el-dropdown-item>
                        <el-dropdown-item @click="updateOrderStatus1">
                          <el-icon>
                            <Select />
                          </el-icon>
                          <span>审核</span>
                        </el-dropdown-item>
                        <el-dropdown-item @click="updateOrderStatus2">
                          <el-icon>
                            <CircleClose />
                          </el-icon>
                          <span>反审核</span>
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
                <div class="tooltip-base-box">
                  <div class="row" style="width: 100px; margin-left: 50px; display: flex; flex-wrap: wrap;">
                    <el-tooltip class="box-item" effect="dark" content="销售出库可以由销售订单传过来，也可以单独创建。" placement="left">
                      <el-icon style="font-size: 22px; color: #E6E6E6;">
                        <QuestionFilled />
                      </el-icon>
                    </el-tooltip>
                  </div>
                </div>
              </div>
  
              <div>
                <div class="ant-spin-nested-loading">
                  <div class="ant-spin-container">
                    <div
                      class="ant-table anr-table-scroll-position-left ant-table-layout-fixed ant-table-middle ant-table-bordered">
                      <div class="ant-table-content">
                        <div class="ant-table-body">
                          <el-table :data="page.records" border stripe v-loading="loading"
                            element-loading-text="Loading..." :element-loading-spinner="svg"
                            element-loading-background="rgba(122, 122, 122, 0.1)"
                            @selection-change="handleSelectionChange" style="width: 100%; max-width: 1800px;">
                            <el-table-column type="selection" width="80" align="center" /><!-- 多选框 -->
  
                            <el-table-column label="操作" width="210" align="center">
                              <template #default="scope">
                                <div style="text-align: center;">
                                  <div class="operation-buttons">
                                    <div class="operation-group">
                                      <a class="operation-link"
                                        @click="orderFind({ cname: '销售订单-详情', path: '/finance/receivables/collectionfind' }, scope.row)">查看</a>
                                      <a class="operation-link"
                                        @click="toUpdate({ cname: '编辑标题', path: '/finance/receivables/collectionupdate' }, scope.row)"v-perm:finance:receivables:collectionupdate>编辑</a>
  
  
                                    </div>
                                    <div class="operation-group">
                                    
                                      <el-popconfirm title="确认删除该项吗？" @confirm="remove(scope.row)">
                                        <template #reference>
                                          <a class="operation-link" v-perm:finance:revenue:revenueremove> 删除</a>
                                        </template>
                                      </el-popconfirm>
                                    </div>
                                  </div>
                                </div>
                              </template>
                            </el-table-column>
  
                            <el-table-column v-if="showIdColumn" prop="id" label="id" width="170" />
                            <el-table-column prop="erpSupplier.supName" label="供应商" width="115" />
                            <el-table-column prop="billNo" label="单据编号" width="243" />
                            <el-table-column prop="billTime" label="单据日期" width="170" />
  
                            <el-table-column prop="erpUser.username" label="操作员" width="150" />
                            <el-table-column prop="erpPerson.perName" label="财务人员" width="120" />
                            <el-table-column prop="erpAccountItems[0].eachAmount" label="收入金额" width="120" />
                            <el-table-column prop="remark" label="备注" width="250" />
                            <el-table-column label="状态" width="100" align="center">
                              <template #default="scope">
                                <el-tag v-if="scope.row.status == 0" type="danger" effect="light">
                                  未审核
                                </el-tag>
                                <el-tag v-else-if="scope.row.status == 1" type="success" effect="light">
                                  已审核
                                </el-tag>
                                <el-tag v-else-if="scope.row.status == 2" type="warning" effect="light">
                                  完成销售
                                </el-tag>
                                <el-tag v-else-if="scope.row.status == 3" type="warning" effect="light">
                                  部分销售
                                </el-tag>
                              </template>
                            </el-table-column>
                          </el-table>
  
                          <el-pagination v-model:page-size="page.size" v-model:current-page="page.current"
                            @current-change="handleCurrentChange" @size-change="handleSizeChange"
                            :page-sizes="[2, 4, 8, 10]" layout="total, sizes, prev, pager, next, jumper"
                            :total="page.total" background style="margin-top:20px;">
                          </el-pagination>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
  
      <el-dialog :destroy-on-close="true" :title="title" v-model="visible" width="1550px" height="500px"
        style="margin-left: 250px;">
        <router-view @close="close" :data="data"></router-view>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { reactive, ref } from 'vue';
  import request from '@/api/request';
  import { ElMessage } from 'element-plus';
  import router from '@/router';
  
  const loading = ref(false);
  const visible = ref(false);
  const title = ref("");
  const data = ref({});
  const page = ref({
    current: 1,
    size: 10,
    total: 0,
    records: []
  });
  const menu = ref({});
  const formInline = reactive({
    region: '',
    customer: '' // 新增客户字段
  });
  const show = ref([]); // 存储客户数据

const loadCushowstomers = () => {
  request({
    url: '/basic/vendor/list',
    method: 'get'
  }).then(res => {

    show.value = res.data; // 更新客户数据
  }).catch(err => {
    console.error(err);
  });
};
loadCushowstomers();
  const selectedIds = ref([]);
  const customers = ref([]);
  const loadCustomers = () => {
    request({
      url: '/basic/vendor/findSuppliers',
      method: 'get'
    }).then(res => {
      console.log(res);
      customers.value = res.data; 
    }).catch(err => {
      console.error(err);
    });
  };
  
  const loadMenus = () => {
    loading.value = true;
  
    request({
      url: '/accountHead/listsk',
      method: "get",
      params: {
        current: page.value.current,
        size: page.value.size,
        billNo:menu.value.billNo,
        billTime:menu.value.billTime,
        organId:menu.value.organId,
        username:menu.value.username,
        handsPersonId:menu.value.handsPersonId,
        accountId:menu.value.accountId,
        status:menu.value.status,
        remark:menu.value.remark,
        type:'收款'
      }
    }).then(res => {
      page.value.records = res.data.records;
      page.value.total = res.data.total;
      console.log(res.data);
  
      // 在成功回调后将 loading 设置为 false，增加延时
      setTimeout(() => {
        loading.value = false;
      }, 100); // 设置1秒的延迟（可以根据需要调整时长）
    }).catch(err => {
      // 发生错误时立即关闭 loading
      loading.value = false;
      console.error(err);
    });
  };
  
  
  
  
  
  
  
  const handleSelectionChange = (val) => {
    selectedIds.value = val.map(item => item.id); // 更新选中的 ID
  };
  
  const deleteSelected = () => {
    if (selectedIds.value.length === 0) {
      ElMessage.warning('请先选择至少一项记录');
      return;
    }
  
    console.log("选中的ID:", selectedIds.value);
  
    request.delete("/accountHead/delete", {
      data: selectedIds.value // 批量删除
    }).then(resp => {
      ElMessage.success('删除成功');
      loadMenus();
      selectedIds.value = []; // 清空选中的 ID
    });
  };
  
  const handleSizeChange = (val) => {
    page.value.size = val;
    page.value.current = 1;
    loadMenus();
  };
  
  const handleCurrentChange = (val) => {
    page.value.current = val;
    loadMenus();
  };
  
  const onReset = () => {
    formInline.region = '';
    formInline.customer = ''; // 重置客户选择
    menu.value = {};
    loadMenus();
  };
  
  const insert = (p) => {
    title.value = p.cname;
    visible.value = true;
    router.push(p.path);
  };
  
  const remove = (row) => {
    request.delete("/accountHead/delete/" + row.id).then(resp => {
      loadMenus();
    });
  
  };
  
  const expanded = ref(false);
  const toggle = () => {
    expanded.value = !expanded.value;
  };
  
  const close = () => {
    visible.value = false;
  };
  
  const toUpdate = (p, row) => {
    title.value = p.cname;
    visible.value = true;
    router.push(p.path);
    data.value = row;
    console.log(row);
  };
  const orderFind = (p, row) => {
    title.value = p.cname;
    visible.value = true;
    router.push(p.path);
    data.value = row;
    console.log(row);
  }
  const Copy = (p) => {
    title.value = p.cname;
    visible.value = true;
    router.push(p.path);
  };
  
  const updateOrderStatus1 = () => {
    console.log("选中的ID:", selectedIds.value);
  
    request.put("/accountHead/updatestatus", {
      ids: selectedIds.value,
      status: "1"
    }).then(resp => {
      ElMessage.success('状态更新成功');
      loadMenus();
    }).catch(error => {
      ElMessage.error('状态更新失败');
      console.error(error);
    });
  };
  
  const updateOrderStatus2 = () => {
    console.log("选中的ID:", selectedIds.value);
  
    request.put("/accountHead/updatestatus", {
      ids: selectedIds.value,
      status: "0"
    }).then(resp => {
      ElMessage.success('状态更新成功');
      loadMenus();
    }).catch(error => {
      ElMessage.error('状态更新失败');
      console.error(error);
    });
  };
  const accounts = ref([]); // 存储结算账户数据
  const loadAccounts = () => {
    request({
      url: '/basic/account/list',
      method: 'get'
    }).then(res => {
      console.log(res);
      accounts.value = res.data; // 更新结算账户数据
    }).catch(err => {
      console.error(err);
    });
  };
  loadAccounts();
  const users = ref({})
  const userfin = () => {
    request({
      url: '/user/user',
      method: 'get'
  
    }).then(res => {
      users.value = res.data
      console.log(res)
    })
  }
  const person = ref({})
  const personfin = () => {
    request({
      url: '/basic/person/list',
      method: 'get'
  
    }).then(res => {
      person.value = res.data
      console.log(res)
    })
  }
  personfin();
  const stausData = [
    { status: '0', stname: '未审核' },
    { status: '1', stname: '已审核' },
    { status: '3', stname: '部分销售' },
    { status: '2', stname: '完成销售' }
  ]
  const stausData2 = [
    { supType: '0', stname: '[供应商]' },
    { supType: '1', stname: '[客户]' },
  
  ]
  // 初始化数据加载
  loadCustomers(); // 加载客户数据
  loadMenus(); // 加载菜单数据
  userfin();//加载操作员数据
  </script>
  
  <style scoped>
  .table-wapper-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .table-operator {
    margin-top: 20px;
  }
  
  .operation-buttons {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .operation-link {
    margin: 0 8px;
    color: #1890ff;
    text-decoration: none;
    cursor: pointer;
  }
  
  .ant-table {
    margin-top: 10px;
    border-radius: 4px;
    overflow: hidden;
  }
  
  .ant-table th,
  .ant-table td {
    padding: 10px;
    text-align: center;
  }
  
  .ant-spin-nested-loading {
    position: relative;
  }
  
  .ant-spin-container {
    padding: 20px;
  }
  
  .ant-table-content {
    overflow-x: auto;
  }
  
  .ant-table-body tr:hover {
    background-color: #e9e9e9;
  }
  </style>